import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Form, Input } from 'antd';
import ModalUtil from '@/utils/modal.js';
import { UserApi } from '@/api/user/api.js';
import FormModal from '@/components/FormModal/index.jsx';

export default forwardRef(function UserFormModal({ onRefresh }, ref) {
  useImperativeHandle(ref, () => ({
    openEdit: (data) => openEdit(data),
    openAdd: () => openAdd(),
    close: () => userRef.current?.close()
  }));

  const [isEdit, setIsEdit] = useState(false);
  const userRef = useRef(null);

  // 打开编辑弹窗
  function openEdit(data) {
    setIsEdit(true);
    userRef.current?.open();
    userRef.current?.form.setFieldsValue(data);
  }

  // 打开新增弹窗
  function openAdd() {
    setIsEdit(false);
    userRef.current?.open();
    userRef.current?.form?.resetFields();
  }

  // 提交表单
  const handleSubmit = async ({ username, password, confirm_password }) => {
    if (password !== confirm_password) {
      ModalUtil.msgWarning('两次输入的密码不一致，请重新输入');
      return;
    }
    const { code } = await UserApi.addUser({
      username: username,
      password: password
    });
    if (code === 0) {
      ModalUtil.msgSuccess('新增用户成功');
      userRef.current?.form?.resetFields();
      onRefresh && onRefresh();
    }
  };

  return (
    <>
      <FormModal
        ref={userRef}
        name="userForm"
        title={isEdit ? '编辑用户' : '新增用户'}
        onFinish={handleSubmit}
        formItems={
          <>
            <Form.Item name="nickname" label="昵称" rules={[{ message: '请输入昵称' }]}>
              <Input />
            </Form.Item>
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirm_password"
              label="确认密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password />
            </Form.Item>
          </>
        }
      />
    </>
  );
});
